import React, { Component } from 'react';
import { Input, Modal } from 'antd';
import './map.css';
const { confirm } = Modal;

interface AMapProps {
  value?: string;
  mapStyle?: any;
}

interface AMapState {
  showError: boolean;
}

let map: any;
let bounds: any;

class TianOpenMapComponent extends Component<AMapProps, AMapState> {
  constructor(props: AMapProps) {
    super(props);
    this.state = {
      showError: false,
    };
  }

  onLoad() {
    const { value } = this.props;
    const parentNode = document.body || document.head;
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=9bde65a82ff7d48d6c107a3e9af63e2e`;
    script.crossOrigin = 'anonymous';

    script.onerror = (e) => {
      // confirm({
      //   title: '地图加载不稳定，请刷新网页重试',
      //   okText: '现在刷新',
      //   cancelText: '知道了',
      //   onOk() {
      //     location.reload();
      //   },
      //   onCancel() {},
      // });
      this.setState({
        showError: true,
      });
    };
    script.onload = () => {
      bounds = new T.LngLatBounds(
        new T.LngLat(116.25183, 27.48391),
        new T.LngLat(119.63013, 29.41568),
      );
      if (document.getElementById('mapcontainer')) {
        map = new T.Map('mapcontainer', {
          minZoom: 8,
          maxZoom: 18,
          projection: 'EPSG:4326',
          maxBounds: bounds,
          center: new T.LngLat(117.942962, 28.455832),
          zoom: 10,
        });
        //初始化
        if (value) {
          const lng_lat = JSON.parse(value);
          const lnglat1 = new T.LngLat(lng_lat[0], lng_lat[1]);
          const mIcon = new T.Icon({
            iconUrl: 'https://ossworkerweb.jxsrnmg.com/worker_supervision_oa/img/marker-blue.png',
            iconSize: new T.Point(20, 35),
          });
          const m_d = new T.Marker(lnglat1, {
            icon: mIcon,
          });
          map.addOverLay(m_d);
          const mzm = map.getZoom();
          if (mzm > 16) {
            map.panTo(lnglat1);
          } else {
            map.panTo(lnglat1, 16);
          }
        }
      }
    };
    parentNode.appendChild(script);
  }

  componentDidMount() {
    this.onLoad();
  }

  render() {
    const { mapStyle } = this.props;
    const { showError } = this.state;
    return (
      <div className="home_div">
        <div id="mapcontainer" className="map" style={mapStyle} />
        {showError && <div className="mapError">地图加载不稳定，请尝试刷新网页重试</div>}
      </div>
    );
  }
}

export default TianOpenMapComponent;
